//
//  BusinessViewController.m
//  Weiweiyunshi
//
//  Created by 王译 on 17/2/10.
//  Copyright © 2017年 王译. All rights reserved.
//

#import "BusinessViewController.h"
#import "TestViewController.h"
#import "BusinessModel.h"
#define POST_URL @"http://server.viviuc.com:8099/CCM/rs/custom/createroom"
@interface BusinessViewController ()<UIWebViewDelegate>
{
    UIWebView *webView;
    NSString *_roomKey;
    NSString *tag;
    TestViewController *vidyo;
}
@end

@implementation BusinessViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createWebView];
//    [self createWebViewLocation];
    [self postRequest];
    [self setUpNav];
    
    // Do any additional setup after loading the view.
}

- (void)setUpNav
{
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"header_back_icon"] style:UIBarButtonItemStyleDone target:self action:@selector(pop)];
    self.navigationItem.leftBarButtonItem = backItem;
    self.navigationItem.title = @"业务";
}


- (void)pop
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

-(void)postRequest{
    if (tag!=nil) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"userId"] = @"Test";
        //    params[@"userId"] = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        //关键参数 roomid 从哪来的 ?
        params[@"roomId"] = tag;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager POST:POST_URL parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            BusinessModel *model = [[BusinessModel alloc]init];
            model = [BusinessModel yy_modelWithDictionary:responseObject];
            _roomKey = model.data[@"vidyoroomkey"];
            vidyo.guestVRoomKey = _roomKey;
            [vidyo showVidyoWeb];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
    }
    //关键代码 设置允许application/json方式请求
    }

-(void)createWebView{

    

    webView = [[UIWebView alloc]initWithFrame:self.view.frame];
                webView.delegate = self;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSLog(@"%@",[userDefaults objectForKey:@"url"]);
                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[userDefaults objectForKey:@"url"]]]];

        [self.view addSubview:webView];

    
}

-(void)createWebViewLocation{
    webView = [[UIWebView alloc]initWithFrame:self.view.frame];
    webView.backgroundColor = [UIColor clearColor];
    //webview.scalesPageToFit =YES;
    webView.delegate =self;
    //找到jsIOS.html文件的路径
    NSString *basePath = [[NSBundle mainBundle]bundlePath];
    NSString *helpHtmlPath = [basePath stringByAppendingPathComponent:@"baidu1.html"];
    NSURL *url = [NSURL fileURLWithPath:helpHtmlPath];
    //加载本地html文件
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
    [self.view addSubview:webView];

}

-(void)enterVidyoRoom{
    vidyo = [[TestViewController alloc]init];
    [self postRequest];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    
    //OC调用JS是基于协议拦截实现的 下面是相关操作
    NSString *absolutePath = request.URL.absoluteString;
    NSLog(@"--->absolutepath---->%@",absolutePath);
    
    NSString *scheme = @"rrcc://";
    
    if ([absolutePath hasPrefix:scheme]) {
        NSString *subPath = [absolutePath substringFromIndex:scheme.length];
        NSLog(@"---->SubPath---->%@",subPath);
        if ([subPath containsString:@"?"]) {//1个或多个参数
            
            if ([subPath containsString:@"&"]) {//多个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                NSArray *params = [parameter componentsSeparatedByString:@"&"];
                
                if (params.count == 2) {
                    if ([self respondsToSelector:sel]) {
                        [self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
                    }
                }
                
                
            } else {//1个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                
                if ([self respondsToSelector:sel]) {
                    [self performSelector:sel withObject:parameter];
                }
                
            }
            
        } else {//没有参数
            NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            NSMutableString *methodNameMu = [NSMutableString stringWithString:methodName];
            NSString *str = @"enterVidyoRoom";
            tag = [methodNameMu stringByReplacingOccurrencesOfString:str withString:@""];
            NSLog(@"唯一标识:%@",tag);
            
            
            SEL sel = NSSelectorFromString(str);
            if ([self respondsToSelector:sel]) {
                [self performSelector:sel];
            }
        }
    }
    
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
